package com.travel.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.travel.entity.TbUser;
import com.travel.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断是不是预检请求
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取请求头部token信息  当将token存入redis后,返回的是uuid
        //uuid
        String token = request.getHeader("token");
        //token工具进行解析
        if(token==null){
            throw new RuntimeException("没有token,未登录");
        }

        //取出存入redis里的(jwt)uuid
        String jwt = (String) redisTemplate.boundValueOps(token).get();
        if (jwt==null){
            throw new RuntimeException("没有jwt令牌,未登录");
        }
        //userName,userPass
        List<String> audience = JWT.decode(jwt).getAudience();
        //根据用户名查询用户信息
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",audience.get(0));
        TbUser user = userMapper.selectOne(wrapper);
        if (user==null){
            throw new RuntimeException("没有token,该用户不存在");
        }
        //再次进行验签: HMAC384加密
        JWTVerifier build = JWT.require(Algorithm.HMAC384(user.getUserPass())).build();
        //进行验签
        build.verify(jwt);
        //根据自定义注解再进行权限判断
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
